package com.guoheng.hazard.common.validator;

import com.guoheng.hazard.common.base.Dict;
import com.guoheng.hazard.sys.mapper.SysDictMapper;

import javax.annotation.Resource;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.List;

/**
 * 类功能描述:　校验数据字典实现
 *
 * @author Eternal
 * @date 2019/6/25 15:07
 */

public class ValidDictValidator implements ConstraintValidator<ValidDict, Object> {

    private String dictType;

    @Resource
    SysDictMapper sysDictMapper;

    @Override
    public void initialize(ValidDict constraintAnnotation) {
        dictType = constraintAnnotation.dictType();
    }

    @Override
    public boolean isValid(Object key, ConstraintValidatorContext constraintValidatorContext) {
        List<Dict> dictList = initDict(dictType);
        boolean result = isInDict(key,dictList);
        if(!result && dictList.size() >0){
            //禁用默认提示信息
            constraintValidatorContext.disableDefaultConstraintViolation();
            //更新提示信息
            constraintValidatorContext.buildConstraintViolationWithTemplate(dictDetails(dictList)).addConstraintViolation();
        }
        return result;
    }

    private List<Dict> initDict(String dictTypeCode){
        return sysDictMapper.getDictValueNameByDictTypeCode(dictTypeCode);
    }

    private static boolean isInDict(Object key,List<Dict> dictList){

        if (null == key || null == dictList || dictList.size()==0) {
            return false;
        }

        for (Dict aDictList : dictList) {
            if (key.toString().equals(aDictList.getDictValueCode())) {
                return true;
            }
        }
        return false;

    }

    private static String dictDetails(List<Dict> dictList){
        String dictTypeName = dictList.get(0).getDictTypeName();
        StringBuilder message = new StringBuilder("数据字典类型:"+ dictTypeName +" [ ");
        for (Dict dict : dictList) {
            message.append(dict.getDictValueCode()).append(":").append(dict.getDictValueName()).append(" ");
        }
        return message + "]";
    }
}
